/**
 * api请求处理
 */
import axios from 'axios';
// import { Message } from 'element-ui'
import axiostore from '@/store/index'

const gl = (global || window);
gl.Msg = false;

// withCredentials 表示跨域请求时是否需要使用凭证
axios.defaults.withCredentials = true
// 使用自定义配置新建一个axios实例
// axios.defaults.timeout = 60000;// 超时时间60s
axios.defaults.timeout = 0;// 超时时间60s
const axiosInstance = axios.create({
  // baseURL: window.APIObj.apiUrl,
  baseURL: process.env.VUE_APP_BASE_API,
});
// 添加请求拦截器
axiosInstance.interceptors.request.use(
  function(config) {
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers.post['Content-Type'] = 'application/json';

    if (config.method == 'get' && config.responseType != 'blob') {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params,
      }
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

// 请求拦截
axiosInstance.interceptors.request.use(
  config => {
    // 发送请求之前的操作
    try {
      let p = config.data ? config.data : config.params;

      let _params = p ? JSON.stringify(p) : 'cancelRequest';
      axiostore.dispatch('axioCancel/offCancel', {
        'method': config.method,
        'url': config.url,
        'params': _params
      })
      // 将pending队列中的请求设置为当前
      config.cancelToken = new axios.CancelToken((cancel) => {
        axiostore.dispatch('axioCancel/pushCancel', {
          'method': config.method,
          'url': config.url,
          'params': _params,
          cancel
        })
      })
    } catch (e) {
      console.info(e);
    }

    return config
  },
  error => {
    // 出来请求错误的处理
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

let flag = true;
// 添加响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    if (response.data.code == 601) {
      window.localStorage.removeItem('user')
      if (flag) {
        Message({
          message: response.data.message,
          type: 'error',
          onClose: () => {
            router.push({
              path: '/login'
            })
          }
        });
      }
      flag = false
      setTimeout(() => {
        flag = true;
      }, 5000);
    }
    return response;
  },
  error => {
    console.log('err' + error) // for debug

    if (error.__CANCEL__) return;

    try {
      Message({
        message: error.message || 'Error',
        type: 'error'
      });
      let config = error.message || error.response.config;
      let p = config.data ? config.data : config.params;
      let _params = p ? JSON.stringify(p) : 'cancelRequest';

      axiostore.dispatch('axioCancel/removeCancel', {
        'method': config.method,
        'url': config.url,
        'params': _params
      })
    } catch (e) {
      console.error(e);
    }
    return Promise.reject(error)
  }
);

export default axiosInstance;
